/*
 * Copyright (c) 2025 Huawei Device, Inc. Ltd. and <马弓手>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "HttpCode.h"
#include "ConnPool.h"
#include "CordovaHttpPlugin.h"
#include "cJSON.h"
#include "FileCache.h"
#include "HttpUrl.h"
#include "CordovaViewController.h"
#include "file/FileUtils.h"
#include <network/netmanager/net_connection.h>
#include <sys/stat.h>

const string CordovaHttpPlugin::LINE_START = "--";
const string CordovaHttpPlugin::LINE_END = "\r\n";
const string CordovaHttpPlugin::BOUNDARY = "+++++";

REGISTER_PLUGIN_CLASS(CordovaHttpPlugin)

CordovaHttpPlugin::CordovaHttpPlugin()
{
    m_nTLSVersion = TLS1_2_VERSION;
}
CordovaHttpPlugin::~CordovaHttpPlugin() 
{
};
bool CordovaHttpPlugin::execute(const string&  action, cJSON* args, CallbackContext cbc) 
{
    if(action == "setServerTrustMode") {
        if(cJSON_GetArraySize(args) > 0) {
            m_strServerTrustMode = cJSON_GetArrayItem(args, 0)->valuestring;
            if(m_strServerTrustMode == "pinned" || m_strServerTrustMode == "legacy") {
                initialize();
                if(!m_strCAFilePathName.empty()) {
                    cbc.success();
                } else {
                    cbc.error("Error:Unfound CA root cer");
                }
            } else {
                m_strCAFilePathName = "";
                m_strServerTrustMode = "nocheck";
                cbc.success();
            }
        }
    }
    
    if(action == "setClientAuthMode") {
        m_strClientCertPathName = "";
        m_strClientKeyPathName = "";
        string strMode = "";
        int nCount = cJSON_GetArraySize(args);
        if(nCount > 0 ) {
            strMode = cJSON_GetArrayItem(args, 0)->valuestring;
        }
        
        string strAlias;
        if(nCount > 1) {
            cJSON* pJson = cJSON_GetArrayItem(args, 1);
            if(pJson->type == cJSON_String) {
                strAlias = cJSON_GetArrayItem(args, 1)->valuestring;
            }
        }
        
        char* pPkcs = NULL; 
        int nLength = 0;
        string strPkcs;
        if(nCount > 2) {
            strPkcs = cJSON_GetArrayItem(args, 2)->valuestring;
            pPkcs = CBase64::decode(strPkcs, nLength);
        }
        
        string strPkcsPassword;
        if(nCount > 3) {
            strPkcsPassword = cJSON_GetArrayItem(args, 3)->valuestring;
        }
        
       string strCertPathName = Application::g_strCachePath + "/cordova_cert.cer";
       if(FileCache::IsFile(strCertPathName, "")) {
            FileCache::deleteFile(strCertPathName);
       }
       string strKeyPathName = Application::g_strCachePath + "/cordova_key.key";
       if(FileCache::IsFile(strKeyPathName, "")) {
            FileCache::deleteFile(strKeyPathName);
       }
        
       if(strMode == "buffer" && !strPkcs.empty() && !strPkcsPassword.empty()) {
            //不支持别名
            if(CSSLSocket::parsePKCS12(pPkcs, nLength, strPkcsPassword.c_str(), strKeyPathName.c_str(), strCertPathName.c_str()) && FileCache::IsFile(strKeyPathName, "") && FileCache::IsFile(strCertPathName, "")) {
                m_strClientCertPathName = strCertPathName;
                m_strClientKeyPathName = strKeyPathName;
                cbc.success();
            } else {
                cbc.error("Couldn't load private key and certificate");
            }
       } 
    }
    
    if(action == "abort") {
        int nReqId = -1;
        if(cJSON_GetArraySize(args) > 0) {
            nReqId = cJSON_GetArrayItem(args, 0)->valueint;
            bool isResult = setHttpRequestThreadAbort(nReqId);
            cJSON* pResponse = cJSON_CreateObject();
            if(isResult) {
                cJSON_AddTrueToObject(pResponse, "aborted");
            } else {
                 cJSON_AddFalseToObject(pResponse, "aborted");
            }
            cbc.success(pResponse);
            cJSON_Delete(pResponse);
        }
    }
    
    if(action == "get") {
        HttpRequest* pHttpRequest = new HttpRequest();
        cJSON* pJson = cJSON_Duplicate(args, 1);
        pHttpRequest->SetCordovaHttpPlugin("GET", this, pJson, cbc);
        pHttpRequest->Start(nullptr);
    }
    
    if(action == "head") {
        HttpRequest* pHttpRequest = new HttpRequest();
        cJSON* pJson = cJSON_Duplicate(args, 1);
        pHttpRequest->SetCordovaHttpPlugin("HEAD", this, pJson, cbc);
        pHttpRequest->Start(nullptr);
    }
    if(action == "delete") {
        HttpRequest* pHttpRequest = new HttpRequest();
        cJSON* pJson = cJSON_Duplicate(args, 1);
        pHttpRequest->SetCordovaHttpPlugin("DELETE", this, pJson, cbc);
        pHttpRequest->Start(nullptr);
    }
    
    if(action == "options") {
        HttpRequest* pHttpRequest = new HttpRequest();
        cJSON* pJson = cJSON_Duplicate(args, 1);
        pHttpRequest->SetCordovaHttpPlugin("OPTIONS", this, pJson, cbc);
        pHttpRequest->Start(nullptr);
    }
    
    if(action == "post") {
        HttpRequest* pHttpRequest = new HttpRequest();
        cJSON* pJson = cJSON_Duplicate(args, 1);
        pHttpRequest->SetCordovaHttpPlugin("POST", this, pJson, cbc);
        pHttpRequest->Start(nullptr);
    }
    
    if(action == "put") {
        HttpRequest* pHttpRequest = new HttpRequest();
        cJSON* pJson = cJSON_Duplicate(args, 1);
        pHttpRequest->SetCordovaHttpPlugin("PUT", this, pJson, cbc);
        pHttpRequest->Start(nullptr);
    }
    
    if(action == "patch") {
        HttpRequest* pHttpRequest = new HttpRequest();
        cJSON* pJson = cJSON_Duplicate(args, 1);
        pHttpRequest->SetCordovaHttpPlugin("PATCH", this, pJson, cbc);
        pHttpRequest->Start(nullptr);
    }
    
    if(action == "uploadFiles") {
        HttpRequest* pHttpRequest = new HttpRequest();
        cJSON* pJson = cJSON_Duplicate(args, 1);
        pHttpRequest->SetCordovaHttpPlugin("UPLOAD", this, pJson, cbc);
        pHttpRequest->Start(nullptr);
    }
    
    if(action == "downloadFile") {
        HttpRequest* pHttpRequest = new HttpRequest();
        cJSON* pJson = cJSON_Duplicate(args, 1);
        pHttpRequest->SetCordovaHttpPlugin("DOWNLOAD", this, pJson, cbc);
        pHttpRequest->Start(nullptr);
    }
    return true;
}

void CordovaHttpPlugin::initialize()
{
    //制作自定义CAFile
    RawDir * pRawDir = OH_ResourceManager_OpenRawDir(Application::g_resourceManager, "certificates");
    int nFileCount = OH_ResourceManager_GetRawFileCount(pRawDir);
    vector<string> vecCAFileContent;
    for(int i=0; i<nFileCount; i++) {
        string strFileName = OH_ResourceManager_GetRawFileName(pRawDir, i);
        if(strFileName.length() > 4) {
            string strTail = strFileName.substr(strFileName.length()-4);
            if(strTail == ".cer") {
                strFileName = "certificates/" + strFileName;
                RawFile *rawfile = OH_ResourceManager_OpenRawFile(Application::g_resourceManager, strFileName.c_str());
                string strFileContent = "";
                const int blockSize = 4096;
                char szBuf[blockSize+1];
                while (true) {
                    memset(szBuf, 0 ,blockSize+1);
                    int ret = OH_ResourceManager_ReadRawFile(rawfile, szBuf, blockSize);
                    if (ret == 0) {
                        break;
                    }
                    strFileContent += szBuf;
                }
                vecCAFileContent.push_back(strFileContent);
                OH_ResourceManager_CloseRawFile(rawfile);
            }
        }
    }
    OH_ResourceManager_CloseRawDir(pRawDir);
    
    HttpUrl::DiffContData<string>(vecCAFileContent);
    if(vecCAFileContent.size() > 0) {
        string strCAFileName = Application::g_strCachePath + "/cordova_CAFile.cer";
        if(FileCache::IsFile(strCAFileName, "")) {
            FileCache::deleteFile(strCAFileName);
        }
        FILE* pFd = FileCache::openFile(strCAFileName, "");
        if(pFd != nullptr) {
            for(int i=0; i<vecCAFileContent.size(); i++) {
                int nTotalWriteSize = 0;
                while(vecCAFileContent[i].length()-nTotalWriteSize > 0) {
                   const char* pContent = vecCAFileContent[i].c_str();
                   int nWriteSize =  FileCache::writeFile(pFd, pContent+nTotalWriteSize, vecCAFileContent[i].length()-nTotalWriteSize);
                   nTotalWriteSize += nWriteSize;
                }
            }
            FileCache::closeFile(pFd);
            m_strCAFilePathName = strCAFileName;
        }
    }
}

void CordovaHttpPlugin::setHttpRequestThread(const HttpRequest* pRequest)
{
    //添加新的任务之前，清除之前已经完成的任务，因为有重定向，所有会出现重复添加的情况，所以在添加之前，要检查是否已经添加过了
    //采用此方案，会永远有一个已经完成的任务驻留在内存中，因任务的内存都是从池里面获取的，只有任务对象驻留，占用极少内存。
    //此方式比创建一个守护线程检测任务完成情况效果更优，
    std::lock_guard<std::mutex> guard(m_mutex);
    bool isExist = false;
    for(auto it = m_vecHttpRequestThread.begin(); it != m_vecHttpRequestThread.end(); ) {
        HttpRequest* pTmp = *it;
        if(!pTmp->IsRunning()) {
            delete pTmp;
            it = m_vecHttpRequestThread.erase(it);
        } else {
            if(pTmp == pRequest) {
                isExist = true;
            }
            ++it;
        }
    }
    
    if(!isExist) {
        m_vecHttpRequestThread.push_back((HttpRequest*)pRequest);
    }
}

bool CordovaHttpPlugin::setHttpRequestThreadAbort(const int nReqId)
{
    std::lock_guard<std::mutex> guard(m_mutex);
    for(int i=0; i<m_vecHttpRequestThread.size(); i++) {
        HttpRequest* pRequest = (HttpRequest*)m_vecHttpRequestThread[i];
        if(pRequest->getReqId() == nReqId) {
            pRequest->setAbort();
            return true;
        }
    }
    return false;
}

bool CordovaHttpPlugin::isNetworkAvailable()
{
    string strTLSVersion = m_preferences->getString("MinTLSSecureSocketProtocols", "TLSv12");
    if(strTLSVersion == "SSLv3") {
        m_nTLSVersion = SSL3_VERSION;
    } else if(strTLSVersion == "TLSv10") {
        m_nTLSVersion = TLS1_VERSION;
    } else if(strTLSVersion == "TLSv11") {
        m_nTLSVersion = TLS1_1_VERSION;
    } else if(strTLSVersion == "TLSv12") {
        m_nTLSVersion = TLS1_2_VERSION;
    } else if(strTLSVersion == "TLSv13") {
        m_nTLSVersion = TLS1_3_VERSION;
    }
    
    int hasDefaultNet;
    int tmp = OH_NetConn_HasDefaultNet(&hasDefaultNet);
    if(tmp != 0) {
        return false;
    }
    NetConn_NetHandle netHandle;
    if(OH_NetConn_GetDefaultNet(&netHandle) != 0) {
       return false;
    }
    NetConn_NetCapabilities netConn_NetCapabilities;
    if(OH_NetConn_GetNetCapabilities(&netHandle, &netConn_NetCapabilities) != 0) {
        return false;
    }
    
    if(netConn_NetCapabilities.bearerTypesSize <= 0) {
        return false;
    }
    
    if(netConn_NetCapabilities.bearerTypes[0] == NETCONN_BEARER_CELLULAR) {
        return true;
    } else if(netConn_NetCapabilities.bearerTypes[0] == NETCONN_BEARER_WIFI) {
        return true;
    } else if(netConn_NetCapabilities.bearerTypes[0] == NETCONN_BEARER_ETHERNET) {
        return true;
    } 
    return true;
}

string CordovaHttpPlugin::getData(const string serializer, cJSON* pJson)
{
    string strBody;
    if (pJson == nullptr) {
      return strBody;
    }

    if (serializer == "json") {
        char* pTmp = cJSON_Print(pJson);
        strBody = pTmp;
        free(pTmp);
    } else if (serializer == "utf8") {
        cJSON* pRet = cJSON_GetObjectItem(pJson, "text");
        if(pRet != nullptr || pRet->type == cJSON_String)
           return pRet->valuestring;
    } else if (serializer == "raw") {
        if(pJson->type == cJSON_String) {
            char* pData = pJson->valuestring;
            strBody = CBase64::decode(pData);
            return strBody;
        }
    } else if(serializer == "urlencoded") {
        cJSON* pNext = pJson->child;
        char szBuf[4096];
        while(pNext) {
            if(!strBody.empty()) {
                strBody += "&";
            }
            if(pNext->type == cJSON_String) {
                sprintf(szBuf, "%s=%s", pNext->string,pNext->valuestring);
                strBody += szBuf;
            }
            
            if(pNext->type == cJSON_Number) {
                sprintf(szBuf, "%s=%f", pNext->string,pNext->valuedouble);
                strBody += szBuf;
            }
            pNext = pNext->next; 
        }
    }
    return strBody;
}

void CordovaHttpPlugin::HttpRequest::Execute(void* arg) 
{
    if(!m_cordovaHttp->isNetworkAvailable()) {
        cJSON* pResponse = cJSON_CreateObject();
        cJSON_AddNumberToObject(pResponse, "status", -6);
        cJSON_AddStringToObject(pResponse, "error", "No network connection available");
        m_cbc.error(pResponse);
        cJSON_Delete(pResponse);
        return;
    }
    
    if(m_strMethod == "POST" || m_strMethod == "PUT" || m_strMethod == "PATCH") {
        void* pTmp = InitThreadData();
        m_cordovaHttp->executeHttpRequestWithData(m_strMethod, m_pArgs, m_cbc, pTmp, m_nTempBufSize, this);
        DeInitThreadData(pTmp);
        cJSON_Delete(m_pArgs);
    }

    if(m_strMethod == "GET" || m_strMethod == "HEAD" || m_strMethod == "DELETE" || m_strMethod == "OPTIONS") {
        void* pTmp = InitThreadData();
        m_cordovaHttp->executeHttpRequestWithoutData(m_strMethod, m_pArgs, m_cbc, pTmp, m_nTempBufSize, this);
        DeInitThreadData(pTmp);
        cJSON_Delete(m_pArgs);
    }
    
    if(m_strMethod == "DOWNLOAD") {
        void* pTmp = InitThreadData();
        m_cordovaHttp->downloadFile(m_pArgs, m_cbc, pTmp, m_nTempBufSize,this);
        DeInitThreadData(pTmp);
        cJSON_Delete(m_pArgs);
    }
    
    if(m_strMethod == "UPLOAD") {
        void* pTmp = InitThreadData();
        m_cordovaHttp->uploadFiles(m_pArgs, m_cbc, pTmp, m_nTempBufSize,this);
        DeInitThreadData(pTmp);
        cJSON_Delete(m_pArgs);
    }
}

void* CordovaHttpPlugin::HttpRequest::InitThreadData()
{
    vector<SMemPage> vecMemBuf;
    ((CMemPool*)Application::g_memPool)->MallocPage(vecMemBuf, 1);
    if(vecMemBuf.size() < 1) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "((CMemPool*)Application::g_memPool)->MallocPage(vecMemBuf, 1) == NULL");
        return NULL;
    }
    m_nTempBufSize = ((CMemPool*)Application::g_memPool)->GetPageSize();
    return vecMemBuf[0].m_point;
}

void CordovaHttpPlugin::HttpRequest::DeInitThreadData(void* pArg)
{
    ((CMemPool*)Application::g_memPool)->FreePage((char*)pArg);
}

bool CordovaHttpPlugin::executeHttpRequestWithData(const string& strMethod, cJSON* pJson, CallbackContext cbc, void* pTmp, const int nBufSize, HttpRequest* pRequest) 
{
    char* pMaxBuffer = (char*)pTmp;
    memset(pMaxBuffer, 0, nBufSize);
    CordovaArgs cordovaArgs(pJson);
    string urlPath = cordovaArgs.getString(0);
    urlPath = urlPath.erase(0, urlPath.find_first_not_of(" "));
    urlPath = urlPath.erase(urlPath.find_last_not_of(" ") + 1);
    cJSON* pData = cordovaArgs.getJSONObject(1);
    string serializer = cordovaArgs.getString(2);
    cJSON* pHeader = cordovaArgs.getJSONObject(3);
    int connectTimeout = cordovaArgs.getInt(4)==0?60:cordovaArgs.getInt(4);
    int readTimeout = cordovaArgs.getInt(5)==0?10000:cordovaArgs.getInt(5)*1000;
    bool followRedirect = cordovaArgs.getBoolean(6);
    string responseType = cordovaArgs.getString(7);
    int reqId = cordovaArgs.getInt(8);
    pRequest->setReqId(reqId);
    setHttpRequestThread(pRequest);
    
    int nPort = 0;
    bool isHttps = false;
    if(urlPath.find("https") == 0 ) {
        nPort = 443;
        isHttps = true;
    } else if(urlPath.find("http") == 0) {
        nPort = 80;
    } else {
        return false;
    }
    
    string requestAddress = "";
    if(urlPath.find("//") != string::npos) {
        requestAddress = urlPath.substr(urlPath.find("//")+2);
    }
    string strDomainAndPort;
    string strDomain;
    if(urlPath.find("//") != string::npos) {
        strDomain = urlPath.substr(urlPath.find("//")+2);
        strDomainAndPort = strDomain;
        if(strDomain.find("/") != string::npos) {
            strDomain = strDomain.substr(0, strDomain.find("/"));
            strDomainAndPort = strDomain;
        }
        if(strDomain.find(":") != string::npos) {
            string strPort = strDomain.substr(strDomain.find(":")+1);
            strDomain = strDomain.substr(0, strDomain.find(":"));
            nPort = atoi(strPort.c_str());
        }    
        requestAddress = requestAddress.substr(strDomainAndPort.length());
    }
    
    string strRequest;
    strRequest = strMethod + " " + requestAddress + " HTTP/1.1\r\n";//%s %s HTTP/1.1\r\n
    
    vector<SMemPage> vecMemBuf;
    ((CMemPool*)Application::g_memPool)->MallocPage(vecMemBuf, 1);
    if(vecMemBuf.size() < 1) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "((CMemPool*)Application::g_memPool)->MallocPage(vecMemBuf, 1) == NULL");
        return false;
    }
    
    char* szBuf = vecMemBuf[0].m_point;
    if(nPort == 80 || nPort == 443)
        sprintf(szBuf, "Host:%s\r\n", strDomain.c_str());
    else
        sprintf(szBuf, "Host:%s:%d\r\n", strDomain.c_str(), nPort);
    strRequest += szBuf;
    
    cJSON* pNext = pHeader->child;
    while(pNext) {
        if(pNext->type == cJSON_String) {
            sprintf(szBuf, "%s:%s\r\n", pNext->string,pNext->valuestring);
            strRequest += szBuf;
        }
        
        if(pNext->type == cJSON_Number) {
            sprintf(szBuf, "%s:%f\r\n", pNext->string,pNext->valuedouble);
            strRequest += szBuf;
        }
        pNext = pNext->next; 
    }
    
    if (serializer == "json") {
        sprintf(szBuf, "Content-Type:application/json\r\n");
        strRequest += szBuf;
    } else if (serializer == "utf8") {
        sprintf(szBuf, "Content-Type:text/plain\r\n");
        strRequest += szBuf;
    } else if (serializer == "raw") {
        sprintf(szBuf, "Content-Type:application/octet-stream\r\n");
        strRequest += szBuf;
    } else if(serializer == "urlencoded") {
        sprintf(szBuf, "Content-Type: application/x-www-form-urlencoded\r\n");
        strRequest += szBuf;
    }
    
    sprintf(szBuf, "Connection:Keep-Alive\r\n");
    strRequest += szBuf;
    
    string strHttpUrl = isHttps?"https://"+strDomainAndPort:"http://"+strDomainAndPort;
    if(Application::g_cookieManage != NULL && !ARKWEB_MEMBER_MISSING(Application::g_cookieManage, existCookies)) {
        if(Application::g_cookieManage->existCookies(false)) {
            if(!ARKWEB_MEMBER_MISSING(Application::g_cookieManage, fetchCookieSync)) {
                char* pCookieValue = NULL;
                Application::g_cookieManage->fetchCookieSync(strHttpUrl.c_str(), false, true, &pCookieValue);
                if(pCookieValue != NULL && strlen(pCookieValue) > 0) {
                    string strCookies = pCookieValue;
                    string strCookie = "Set-Cookie:";
                    size_t pos;
                    while ((pos = strCookies.find(strCookie)) != std::string::npos) {
                        strCookies.erase(pos, strCookie.length());
                    }
                    sprintf(szBuf, "Cookie:%s\r\n", strCookies.c_str());
                    strRequest += szBuf;
                }
                if(pCookieValue != NULL) {
                    OH_ArkWeb_ReleaseString(pCookieValue);
                }    
            }
        }
    }
    
    string strBody = getData(serializer, pData);
    
    if(!strBody.empty()) {
        sprintf(szBuf, "Keep-Alive:timeout=5, max=1000\r\n");
        strRequest += szBuf;
        sprintf(szBuf, "Content-Length:%lu\r\n\r\n", strBody.size());
        strRequest += szBuf;
        strRequest += strBody;
    } else {
        sprintf(szBuf, "Keep-Alive:timeout=5, max=1000\r\n\r\n");
        strRequest += szBuf;
    }
    ((CMemPool*)Application::g_memPool)->FreePage(vecMemBuf);
    
    bool isHttpProxy = false;
    NetConn_HttpProxy httpProxy;
    memset(httpProxy.host, 0 ,sizeof(httpProxy.host));
    httpProxy.port = 0;
    if(OH_NetConn_GetDefaultHttpProxy(&httpProxy) == 0) {
        if(strlen(httpProxy.host) > 0 && httpProxy.port != 0) {
            isHttpProxy = true;
            isHttps = false;
        }
    }
    
    if(isHttpProxy) {
        strDomain = httpProxy.host;
        nPort = httpProxy.port;
    }
    
    ConnPoolManage* connPoolManage = (ConnPoolManage*)Application::g_connPoolManage;
    ConnPool* pool = connPoolManage->getConnPool(strDomain);
    if(pool == NULL) {
        return false;
    }
    
    //加载资源尝试5次连接服务器
    vector<SMemPage> vecMemPage;
    if(isHttps) {
        bool isClose = false;
        SSL* ssl = NULL;
        if(!pool->getSSL(&ssl, nPort, m_nTLSVersion, connectTimeout, m_strCAFilePathName, m_strClientCertPathName, m_strClientKeyPathName)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->getSSL(&ssl, nPort, connectTimeout, m_strCAFilePathName, m_strClientCertPathName, m_strClientKeyPathName) == false");
        }else if(!pool->sendWithTimeOut(ssl, strRequest, std::ref(pRequest->getAbort()))) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->sendWithTimeOut(ssl, strRequest) == false");
        }else if(!pool->recvHttpWithTimeOut(ssl, strMethod, vecMemPage, pMaxBuffer, nBufSize,isClose, std::ref(pRequest->getAbort()), readTimeout)) {
            ((CMemPool*)Application::g_memPool)->FreePage(vecMemPage);
        }
        pool->freeSocket(ssl, true);
    } else {
        bool isClose = false;
        int nSocket = -1;
        if(!pool->getSocket(nSocket, nPort, connectTimeout)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->getSocket(&nSocket) == false");
        }else if(!pool->sendWithTimeOut(nSocket, strRequest, std::ref(pRequest->getAbort()))) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->sendWithTimeOut(nSocket, strRequest) == false");
        }else if(!pool->recvHttpWithTimeOut(nSocket, strMethod, vecMemPage, pMaxBuffer, nBufSize,isClose, std::ref(pRequest->getAbort()), readTimeout)) {
            ((CMemPool*)Application::g_memPool)->FreePage(vecMemPage);
        }
        pool->freeSocket(nSocket, true);
    }
    
    if(vecMemPage.size() == 0) {
        OH_LOG_Print(LOG_APP, LOG_WARN, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "vecMemPage.size() == 0");
        return false;
    }
    
    int httpCode = pool->getHttpCode(vecMemPage[0].m_point, vecMemPage[0].m_nCount);
    if(httpCode == 0) {
        ((CMemPool*)Application::g_memPool)->FreePage(vecMemPage);
        return false;
    }
    
    if(followRedirect && HttpCode::isRedirection(httpCode)) {
        string strLocation = pool->getHttpLocation(vecMemPage[0].m_point, vecMemPage[0].m_nCount);
        if(!strLocation.empty() && strLocation != urlPath) {
            cJSON* pUrl = cJSON_CreateString(strLocation.c_str());
            cJSON_ReplaceItemInArray(pJson, 0, pUrl);
            executeHttpRequestWithData(strMethod,pJson,cbc,pTmp, nBufSize, pRequest);
        }
        return true;
    }
    
    map<string, string> mapRespHeaders;
    if(!pool->getHttpHeaders(vecMemPage[0].m_point, vecMemPage[0].m_nCount,mapRespHeaders)) {
        ((CMemPool*)Application::g_memPool)->FreePage(vecMemPage);
        return false;
    }
    
    cJSON* pResponseHeader = cJSON_CreateObject();
    for(map<string,string>::iterator iter = mapRespHeaders.begin(); iter != mapRespHeaders.end(); ++iter){
        cJSON_AddStringToObject(pResponseHeader, iter->first.c_str(), iter->second.c_str());
    }
    cJSON* pResponse = cJSON_CreateObject();
    cJSON_AddNumberToObject(pResponse, "status", httpCode);
    cJSON_AddStringToObject(pResponse, "url", urlPath.c_str());
    cJSON_AddItemToObject(pResponse, "headers", pResponseHeader);
    
   vector<char> vecResponseBody;
    int nBodyPos = pool->getHttpHeader(vecMemPage[0].m_point, vecMemPage[0].m_nCount);
    for(int i=0; i<vecMemPage.size(); i++) {
        char* pResData = NULL;
        int nResLength = 0;
        if(i == 0)  {
            pResData = vecMemPage[i].m_point + nBodyPos;
            nResLength = vecMemPage[i].m_nCount - nBodyPos;
            
        } else {
            pResData = vecMemPage[i].m_point;
            nResLength = vecMemPage[i].m_nCount;
        }
       vecResponseBody.insert(vecResponseBody.end(), pResData, pResData+nResLength);
    }
    
    if(responseType == "text" || responseType == "json") {
        string strResponseBody;//返回默认utf-8编码
        strResponseBody.insert(strResponseBody.begin(), vecResponseBody.begin(), vecResponseBody.begin()+vecResponseBody.size());
        cJSON_AddStringToObject(pResponse, "data", strResponseBody.c_str());
    } else {
        string strResponseBody = CBase64::encode((char*)&vecResponseBody[0], vecResponseBody.size());
        cJSON_AddStringToObject(pResponse, "data", strResponseBody.c_str());
    }
    cbc.success(pResponse);
    cJSON_Delete(pResponse);
    return true;
}

bool CordovaHttpPlugin::executeHttpRequestWithoutData(const string& strMethod, cJSON* pJson, CallbackContext cbc, void* pTmp, const int nBufSize, HttpRequest* pRequest)
{
    char* pMaxBuffer = (char*)pTmp;
    memset(pMaxBuffer, 0, nBufSize);
    CordovaArgs cordovaArgs(pJson);
    string urlPath = cordovaArgs.getString(0);
    urlPath = urlPath.erase(0, urlPath.find_first_not_of(" "));
    urlPath = urlPath.erase(urlPath.find_last_not_of(" ") + 1);
    cJSON* pHeader = cordovaArgs.getJSONObject(1);
    int connectTimeout = cordovaArgs.getInt(2)==0?60:cordovaArgs.getInt(2);
    int readTimeout = cordovaArgs.getInt(3)==0?60000:cordovaArgs.getInt(3)*1000;
    bool followRedirect = cordovaArgs.getBoolean(4);
    string responseType = cordovaArgs.getString(5);
    int reqId = cordovaArgs.getInt(6);
    pRequest->setReqId(reqId);
    setHttpRequestThread(pRequest);
    
    int nPort = 0;
    bool isHttps = false;
    if(urlPath.find("https") == 0 ) {
        nPort = 443;
        isHttps = true;
    } else if(urlPath.find("http") == 0) {
        nPort = 80;
    } else {
        return false;
    }
    
    string requestAddress = "";
    if(urlPath.find("//") != string::npos) {
        requestAddress = urlPath.substr(urlPath.find("//")+2);
    }
    string strDomainAndPort;
    string strDomain;
    if(urlPath.find("//") != string::npos) {
        strDomain = urlPath.substr(urlPath.find("//")+2);
        strDomainAndPort = strDomain;
        if(strDomain.find("/") != string::npos) {
            strDomain = strDomain.substr(0, strDomain.find("/"));
            strDomainAndPort = strDomain;
        }
        if(strDomain.find(":") != string::npos) {
            string strPort = strDomain.substr(strDomain.find(":")+1);
            strDomain = strDomain.substr(0, strDomain.find(":"));
            nPort = atoi(strPort.c_str());
        }    
        requestAddress = requestAddress.substr(strDomainAndPort.length());
    }
    
    string strRequest;
    strRequest = strMethod + " " + requestAddress + " HTTP/1.1\r\n";//%s %s HTTP/1.1\r\n
    
    vector<SMemPage> vecMemBuf;
    ((CMemPool*)Application::g_memPool)->MallocPage(vecMemBuf, 1);
    if(vecMemBuf.size() < 1) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "((CMemPool*)Application::g_memPool)->MallocPage(vecMemBuf, 1) == NULL");
        return false;
    }
    
    char* szBuf = vecMemBuf[0].m_point;
    if(nPort == 80 || nPort == 443)
        sprintf(szBuf, "Host:%s\r\n", strDomain.c_str());
    else
        sprintf(szBuf, "Host:%s:%d\r\n", strDomain.c_str(), nPort);
    strRequest += szBuf;
    
    cJSON* pNext = pHeader->child;
    while(pNext) {
        if(pNext->type == cJSON_String) {
            sprintf(szBuf, "%s:%s\r\n", pNext->string,pNext->valuestring);
            strRequest += szBuf;
        }
        
        if(pNext->type == cJSON_Number) {
            sprintf(szBuf, "%s:%f\r\n", pNext->string,pNext->valuedouble);
            strRequest += szBuf;
        }
        pNext = pNext->next; 
    }
    
    sprintf(szBuf, "Connection:Keep-Alive\r\n");
    strRequest += szBuf;
    
    string strHttpUrl = isHttps?"https://"+strDomainAndPort:"http://"+strDomainAndPort;
    if(Application::g_cookieManage != NULL && !ARKWEB_MEMBER_MISSING(Application::g_cookieManage, existCookies)) {
        if(Application::g_cookieManage->existCookies(false)) {
            if(!ARKWEB_MEMBER_MISSING(Application::g_cookieManage, fetchCookieSync)) {
                char* pCookieValue = NULL;
                Application::g_cookieManage->fetchCookieSync(strHttpUrl.c_str(), false, true, &pCookieValue);
                if(pCookieValue != NULL && strlen(pCookieValue) > 0) {
                    string strCookies = pCookieValue;
                    string strCookie = "Set-Cookie:";
                    size_t pos;
                    while ((pos = strCookies.find(strCookie)) != std::string::npos) {
                        strCookies.erase(pos, strCookie.length());
                    }
                    sprintf(szBuf, "Cookie:%s\r\n", strCookies.c_str());
                    strRequest += szBuf;
                }
                if(pCookieValue != NULL) {
                    OH_ArkWeb_ReleaseString(pCookieValue);
                }    
            }
        }
    }
    
    sprintf(szBuf, "Keep-Alive:timeout=5, max=1000\r\n\r\n");
    strRequest += szBuf;
    ((CMemPool*)Application::g_memPool)->FreePage(vecMemBuf);
    
    bool isHttpProxy = false;
    NetConn_HttpProxy httpProxy;
    memset(httpProxy.host, 0 ,sizeof(httpProxy.host));
    httpProxy.port = 0;
    if(OH_NetConn_GetDefaultHttpProxy(&httpProxy) == 0) {
        if(strlen(httpProxy.host) > 0 && httpProxy.port != 0) {
            isHttpProxy = true;
            isHttps = false;
        }
    }
    
    if(isHttpProxy) {
        strDomain = httpProxy.host;
        nPort = httpProxy.port;
    }
    
    ConnPoolManage* connPoolManage = (ConnPoolManage*)Application::g_connPoolManage;
    ConnPool* pool = connPoolManage->getConnPool(strDomain);
    if(pool == NULL) {
        return false;
    }
    
    map<string, string>  mapRespHeaders;
    string strCachePath = Application::g_strCachePath;
    string strRequestFileName =  "";
    strRequestFileName = "/"+HttpUrl::generateMD5(urlPath);
    struct stat file_stat;
    string strFile = strCachePath + strRequestFileName;
    if (stat(strFile.c_str(), &file_stat) == 0) {
        time_t file_mtime = file_stat.st_mtime;
        time_t current_time;
        time(&current_time);
        double dbDiffSeconds = difftime(current_time, file_mtime);
        if(dbDiffSeconds > ((CordovaViewController*)Application::g_cordovaViewController)->getCordovaCacheDuration()) {
            FileCache::deleteFile(strCachePath+strRequestFileName);
        }
    }
    
    if(isHttps) {
        bool isClose = false;
        SSL* ssl = NULL;
        if(!pool->getSSL(&ssl, nPort, m_nTLSVersion, connectTimeout, m_strCAFilePathName, m_strClientCertPathName, m_strClientKeyPathName)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->getSSL(&ssl, nPort, m_strCAFilePathName, m_strClientCertPathName, m_strClientKeyPathName) == false");
        }else if(!pool->sendWithTimeOut(ssl, strRequest, std::ref(pRequest->getAbort()))) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->sendWithTimeOut(ssl, strRequest) == false");
        }else if(!pool->recvHttpWithTimeOut(ssl, strMethod, strRequestFileName, mapRespHeaders, strCachePath, pMaxBuffer, nBufSize, isClose, std::ref(pRequest->getAbort()), NULL, readTimeout)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->recvHttpWithTimeOut(ssl, strRequestFileName, mapRespHeaders, pMaxBuffer, nBufSize, isReconnect) == false");
        }
        pool->freeSocket(ssl, true);
    } else {
        bool isClose = false;
        int nSocket = -1;
        if(!pool->getSocket(nSocket, nPort, connectTimeout)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->getSocket(nSocket) == false");
        } else if(!pool->sendWithTimeOut(nSocket, strRequest, std::ref(pRequest->getAbort()))) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->sendWithTimeOut(nSocket, strRequest) == false");
        } else if(!pool->recvHttpWithTimeOut(nSocket, strMethod, strRequestFileName, mapRespHeaders, strCachePath, pMaxBuffer, nBufSize, isClose, std::ref(pRequest->getAbort()), NULL, readTimeout)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->recvHttpWithTimeOut(nSocket, strRequestFileName, pMaxBuffer, nBufSize, isReconnect) == false");
        }
        pool->freeSocket(nSocket, true);
    }
    
    if(pRequest->getAbort()) {
        cJSON* pResponse = cJSON_CreateObject();
        cJSON_AddNumberToObject(pResponse, "status", -8);
        cbc.success(pResponse);
        cJSON_Delete(pResponse);
        return true;
    }
    
    int httpCode = pool->getHttpCode((char*)pMaxBuffer, strlen((char*)pMaxBuffer));
    if(httpCode == 0) {
        return false;
    }
    
    if(followRedirect && HttpCode::isRedirection(httpCode)) {
        string strLocation = pool->getHttpLocation((char*)pMaxBuffer, strlen((char*)pMaxBuffer));
        if(!strLocation.empty() && strLocation != urlPath) {
            cJSON* pUrl = cJSON_CreateString(strLocation.c_str());
            cJSON_ReplaceItemInArray(pJson, 0, pUrl);
            executeHttpRequestWithoutData(strMethod, pJson,cbc,pTmp, nBufSize, pRequest);
            return true;
        }
    }
    
    if(!FileCache::IsFile(strRequestFileName, strCachePath)) {
        return false;
    }
    
    cJSON* pResponseHeader = cJSON_CreateObject();
    for(map<string,string>::iterator iter = mapRespHeaders.begin(); iter != mapRespHeaders.end(); ++iter){
        cJSON_AddStringToObject(pResponseHeader, iter->first.c_str(), iter->second.c_str());
    }
    cJSON* pResponse = cJSON_CreateObject();
    cJSON_AddNumberToObject(pResponse, "status", httpCode);
    cJSON_AddStringToObject(pResponse, "url", urlPath.c_str());
    cJSON_AddItemToObject(pResponse, "headers", pResponseHeader);
    
     FILE* file = FileCache::openFile(strRequestFileName,strCachePath);
    if(file == NULL) {
        return false;
    }
    
    vector<SMemPage> vecMemPage;
    const int blockSize = ((CMemPool*)Application::g_memPool)->GetPageSize();
    long consumed = 0;
    ((CMemPool*)Application::g_memPool)->MallocPage(vecMemPage, 1);
    if(vecMemPage.size() < 1) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "((CMemPool*)Application::g_memPool)->MallocPage(vecMemPage, 1) == NULL");
        return false;
    }
    unsigned  char* buffer = (unsigned  char*)vecMemPage[0].m_point;
    vector<char> vecResponseBody;
    while (true) {
        int ret = FileCache::readFile(file, buffer, blockSize, consumed);
        OH_LOG_INFO(LOG_APP, "read cacheFile %{public}d bytes.", ret);
        if (ret == 0) {
            break;
        }
        consumed += ret;
        vecResponseBody.insert(vecResponseBody.end(), (char*)buffer, (char*)buffer+ret);
        memset(buffer, 0, blockSize);
    }
    ((CMemPool*)Application::g_memPool)->FreePage(vecMemPage);
    FileCache::closeFile(file);
    if(responseType == "text" || responseType == "json") {
        string strResponseBody;//默认utf8编码
        strResponseBody.insert(strResponseBody.begin(), vecResponseBody.begin(), vecResponseBody.begin()+vecResponseBody.size());
        cJSON_AddStringToObject(pResponse, "data", strResponseBody.c_str());
    } else {
        string strResponseBody = CBase64::encode((char*)&vecResponseBody[0], vecResponseBody.size());
        cJSON_AddStringToObject(pResponse, "data", strResponseBody.c_str());
    }
    cbc.success(pResponse);
    cJSON_Delete(pResponse);
    return true;
}

bool CordovaHttpPlugin::downloadFile(cJSON* pJson, CallbackContext cbc, void* pTmp, const int nBufSize, HttpRequest* pRequest)
{
    char* pMaxBuffer = (char*)pTmp;
    memset(pMaxBuffer, 0, nBufSize);
    CordovaArgs cordovaArgs(pJson);
    string urlPath = cordovaArgs.getString(0);
    urlPath = urlPath.erase(0, urlPath.find_first_not_of(" "));
    urlPath = urlPath.erase(urlPath.find_last_not_of(" ") + 1);
    cJSON* pHeader = cordovaArgs.getJSONObject(1);
    string strFilePath = cordovaArgs.getString(2);
    int connectTimeout = cordovaArgs.getInt(3)==0?60:cordovaArgs.getInt(3);
    int readTimeout = cordovaArgs.getInt(4)==0?60000:cordovaArgs.getInt(4)*1000;
    bool followRedirect = cordovaArgs.getBoolean(5);
    int reqId = cordovaArgs.getInt(6);
    pRequest->setReqId(reqId);
    setHttpRequestThread(pRequest);
    
    int nPort = 0;
    bool isHttps = false;
    if(urlPath.find("https") == 0 ) {
        nPort = 443;
        isHttps = true;
    } else if(urlPath.find("http") == 0) {
        nPort = 80;
    } else {
        return false;
    }
    
    string requestAddress = "";
    if(urlPath.find("//") != string::npos) {
        requestAddress = urlPath.substr(urlPath.find("//")+2);
    }
    string strDomainAndPort;
    string strDomain;
    if(urlPath.find("//") != string::npos) {
        strDomain = urlPath.substr(urlPath.find("//")+2);
        strDomainAndPort = strDomain;
        if(strDomain.find("/") != string::npos) {
            strDomain = strDomain.substr(0, strDomain.find("/"));
            strDomainAndPort = strDomain;
        }
        if(strDomain.find(":") != string::npos) {
            string strPort = strDomain.substr(strDomain.find(":")+1);
            strDomain = strDomain.substr(0, strDomain.find(":"));
            nPort = atoi(strPort.c_str());
        }    
        requestAddress = requestAddress.substr(strDomainAndPort.length());
    }
    
    string strRequest;
    strRequest = "GET " + requestAddress + " HTTP/1.1\r\n";//%s %s HTTP/1.1\r\n
    
    vector<SMemPage> vecMemBuf;
    ((CMemPool*)Application::g_memPool)->MallocPage(vecMemBuf, 1);
    if(vecMemBuf.size() < 1) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "((CMemPool*)Application::g_memPool)->MallocPage(vecMemBuf, 1) == NULL");
        return false;
    }
    
    char* szBuf = vecMemBuf[0].m_point;
    if(nPort == 80 || nPort == 443)
        sprintf(szBuf, "Host:%s\r\n", strDomain.c_str());
    else
        sprintf(szBuf, "Host:%s:%d\r\n", strDomain.c_str(), nPort);
    strRequest += szBuf;
    
    cJSON* pNext = pHeader->child;
    while(pNext) {
        if(pNext->type == cJSON_String) {
            sprintf(szBuf, "%s:%s\r\n", pNext->string,pNext->valuestring);
            strRequest += szBuf;
        }
        
        if(pNext->type == cJSON_Number) {
            sprintf(szBuf, "%s:%f\r\n", pNext->string,pNext->valuedouble);
            strRequest += szBuf;
        }
        pNext = pNext->next; 
    }
    
    sprintf(szBuf, "Connection:Keep-Alive\r\n");
    strRequest += szBuf;
    
    string strHttpUrl = isHttps?"https://"+strDomainAndPort:"http://"+strDomainAndPort;
    if(Application::g_cookieManage != NULL && !ARKWEB_MEMBER_MISSING(Application::g_cookieManage, existCookies)) {
        if(Application::g_cookieManage->existCookies(false)) {
            if(!ARKWEB_MEMBER_MISSING(Application::g_cookieManage, fetchCookieSync)) {
                char* pCookieValue = NULL;
                Application::g_cookieManage->fetchCookieSync(strHttpUrl.c_str(), false, true, &pCookieValue);
                if(pCookieValue != NULL && strlen(pCookieValue) > 0) {
                    string strCookies = pCookieValue;
                    string strCookie = "Set-Cookie:";
                    size_t pos;
                    while ((pos = strCookies.find(strCookie)) != std::string::npos) {
                        strCookies.erase(pos, strCookie.length());
                    }
                    sprintf(szBuf, "Cookie:%s\r\n", strCookies.c_str());
                    strRequest += szBuf;
                }
                if(pCookieValue != NULL) {
                    OH_ArkWeb_ReleaseString(pCookieValue);
                }    
            }
        }
    }
    
    sprintf(szBuf, "Keep-Alive:timeout=5, max=1000\r\n\r\n");
    strRequest += szBuf;
    ((CMemPool*)Application::g_memPool)->FreePage(vecMemBuf);
    
    bool isHttpProxy = false;
    NetConn_HttpProxy httpProxy;
    memset(httpProxy.host, 0 ,sizeof(httpProxy.host));
    httpProxy.port = 0;
    if(OH_NetConn_GetDefaultHttpProxy(&httpProxy) == 0) {
        if(strlen(httpProxy.host) > 0 && httpProxy.port != 0) {
            isHttpProxy = true;
            isHttps = false;
        }
    }
    
    if(isHttpProxy) {
        strDomain = httpProxy.host;
        nPort = httpProxy.port;
    }
    
    ConnPoolManage* connPoolManage = (ConnPoolManage*)Application::g_connPoolManage;
    ConnPool* pool = connPoolManage->getConnPool(strDomain);
    if(pool == NULL) {
        return false;
    }
    
    map<string, string>  mapRespHeaders;
    string strCachePath = Application::g_strCachePath;
    string strRequestFileName =  "";
    strRequestFileName = "/"+HttpUrl::generateMD5(urlPath);
    struct stat file_stat;
    string strFile = strCachePath + strRequestFileName;
    if (stat(strFile.c_str(), &file_stat) == 0) {
        time_t file_mtime = file_stat.st_mtime;
        time_t current_time;
        time(&current_time);
        double dbDiffSeconds = difftime(current_time, file_mtime);
        if(dbDiffSeconds > ((CordovaViewController*)Application::g_cordovaViewController)->getCordovaCacheDuration()) {
            FileCache::deleteFile(strCachePath+strRequestFileName);
        }
    }
    
    if(isHttps) {
        bool isClose = false;
        SSL* ssl = NULL;
        if(!pool->getSSL(&ssl, nPort, m_nTLSVersion, connectTimeout, m_strCAFilePathName, m_strClientCertPathName, m_strClientKeyPathName)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->getSSL(&ssl, nPort, m_strCAFilePathName, m_strClientCertPathName, m_strClientKeyPathName) == false");
        }else if(!pool->sendWithTimeOut(ssl, strRequest, std::ref(pRequest->getAbort()))) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->sendWithTimeOut(ssl, strRequest) == false");
        }else if(!pool->recvHttpWithTimeOut(ssl, "GET", strRequestFileName, mapRespHeaders, strCachePath, pMaxBuffer, nBufSize, isClose, std::ref(pRequest->getAbort()), NULL, readTimeout)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->recvHttpWithTimeOut(ssl, strRequestFileName, mapRespHeaders, pMaxBuffer, nBufSize, isReconnect) == false");
        }
        pool->freeSocket(ssl, true);
    } else {
        bool isClose = false;
        int nSocket = -1;
        if(!pool->getSocket(nSocket, nPort, connectTimeout)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->getSocket(nSocket) == false");
        }else if(!pool->sendWithTimeOut(nSocket, strRequest, std::ref(pRequest->getAbort()))) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->sendWithTimeOut(nSocket, strRequest) == false");
        }else if(!pool->recvHttpWithTimeOut(nSocket, "GET", strRequestFileName, mapRespHeaders, strCachePath, pMaxBuffer, nBufSize, isClose, std::ref(pRequest->getAbort()), NULL, readTimeout)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin","pool->recvHttpWithTimeOut(nSocket, strRequestFileName, pMaxBuffer, nBufSize, isReconnect) == false");
        }
        pool->freeSocket(nSocket, true);
    }
    
    if(pRequest->getAbort()) {
        cJSON* pResponse = cJSON_CreateObject();
        cJSON_AddNumberToObject(pResponse, "status", -8);
        cJSON_AddStringToObject(pResponse, "error", "User canceled");
        cbc.error(pResponse);
        cJSON_Delete(pResponse);
        return true;
    }
    
    int httpCode = pool->getHttpCode((char*)pMaxBuffer, strlen((char*)pMaxBuffer));
    if(httpCode == 0) {
        return false;
    }
    
    if(followRedirect && HttpCode::isRedirection(httpCode)) {
        string strLocation = pool->getHttpLocation((char*)pMaxBuffer, strlen((char*)pMaxBuffer));
        if(!strLocation.empty() && strLocation != urlPath) {
            cJSON* pUrl = cJSON_CreateString(strLocation.c_str());
            cJSON_ReplaceItemInArray(pJson, 0, pUrl);
            downloadFile(pJson,cbc,pTmp, nBufSize, pRequest);
        }
        return true;
    }
    
    if(!FileCache::IsFile(strRequestFileName, strCachePath)) {
        return false;
    }
    
    if(!FileCache::moveFile(strCachePath+strRequestFileName, strFilePath)) {
        return false;
    }
    
    cJSON* pFileEntry = FileUtils::makeEntryForUrl(strFilePath);
    
    cJSON* pResponseHeader = cJSON_CreateObject();
    for(map<string,string>::iterator iter = mapRespHeaders.begin(); iter != mapRespHeaders.end(); ++iter){
        cJSON_AddStringToObject(pResponseHeader, iter->first.c_str(), iter->second.c_str());
    }
    cJSON* pResponse = cJSON_CreateObject();
    cJSON_AddNumberToObject(pResponse, "status", httpCode);
    cJSON_AddStringToObject(pResponse, "url", urlPath.c_str());
    cJSON_AddItemToObject(pResponse, "headers", pResponseHeader);
    cJSON_AddItemToObject(pResponse, "file", pFileEntry);
    cbc.success(pResponse);
    cJSON_Delete(pResponse);
    return true;
}

bool CordovaHttpPlugin::uploadFiles(cJSON* pJson, CallbackContext cbc, void* pTmp, const int nBufSize, HttpRequest* pRequest)
{
    char* pMaxBuffer = (char*)pTmp;
    memset(pMaxBuffer, 0, nBufSize);
    CordovaArgs cordovaArgs(pJson);
    string urlPath = cordovaArgs.getString(0);
    urlPath = urlPath.erase(0, urlPath.find_first_not_of(" "));
    urlPath = urlPath.erase(urlPath.find_last_not_of(" ") + 1);
    cJSON* pHeader = cordovaArgs.getJSONObject(1);
    cJSON* pFilePath = cordovaArgs.getJSONObject(2);
    cJSON* uploadNames = cordovaArgs.getJSONObject(3);
    int connectTimeout = cordovaArgs.getInt(4)==0?60:cordovaArgs.getInt(4);
    int readTimeout = cordovaArgs.getInt(5)==0?60000:cordovaArgs.getInt(5)*1000;
    bool followRedirect = cordovaArgs.getBoolean(6);
    string responseType = cordovaArgs.getString(7);
    int reqId = cordovaArgs.getInt(8);
    pRequest->setReqId(reqId);
    setHttpRequestThread(pRequest);
    
    int nPort = 0;
    bool isHttps = false;
    if(urlPath.find("https") == 0 ) {
        nPort = 443;
        isHttps = true;
    } else if(urlPath.find("http") == 0) {
        nPort = 80;
    } else {
        return false;
    }
    
    string requestAddress = "";
    if(urlPath.find("//") != string::npos) {
        requestAddress = urlPath.substr(urlPath.find("//")+2);
    }
    string strDomainAndPort;
    string strDomain;
    if(urlPath.find("//") != string::npos) {
        strDomain = urlPath.substr(urlPath.find("//")+2);
        strDomainAndPort = strDomain;
        if(strDomain.find("/") != string::npos) {
            strDomain = strDomain.substr(0, strDomain.find("/"));
            strDomainAndPort = strDomain;
        }
        if(strDomain.find(":") != string::npos) {
            string strPort = strDomain.substr(strDomain.find(":")+1);
            strDomain = strDomain.substr(0, strDomain.find(":"));
            nPort = atoi(strPort.c_str());
        }    
        requestAddress = requestAddress.substr(strDomainAndPort.length());
    }
    
    
    bool isHttpProxy = false;
    NetConn_HttpProxy httpProxy;
    memset(httpProxy.host, 0 ,sizeof(httpProxy.host));
    httpProxy.port = 0;
    if(OH_NetConn_GetDefaultHttpProxy(&httpProxy) == 0) {
        if(strlen(httpProxy.host) > 0 && httpProxy.port != 0) {
            isHttpProxy = true;
            isHttps = false;
        }
    }
    
    if(isHttpProxy) {
        strDomain = httpProxy.host;
        nPort = httpProxy.port;
    }
    
    int nCount  = cJSON_GetArraySize(pFilePath);
    if(nCount != cJSON_GetArraySize(uploadNames)) {
        return false;
    }
  
    int nFileSize = 0;
    vector<string> vecRequestParams;
    vector<string> vecFilePath;
    for(int i=0; i<nCount; i++) {
        string strFilePath = cJSON_GetArrayItem(pFilePath, i)->valuestring;
        string strFileValue = strFilePath;
        if(strFilePath.find_last_of("/") != string::npos) {
            strFileValue = strFilePath.substr(strFilePath.find_last_of("/")+1);
        }
        string strFileName = cJSON_GetArrayItem(uploadNames, i)->valuestring;
        string strMimeType = FileUtils::getMimeType(strFilePath);
        string strRequestParams;
        strRequestParams += (LINE_START + BOUNDARY + LINE_END);
        strRequestParams += "Content-Disposition:form-data;name=\"";
        strRequestParams += strFileName;
        strRequestParams += "\";";
        strRequestParams += " filename=\"";
        strRequestParams += strFileValue;
        strRequestParams += "\"";
        strRequestParams += LINE_END;
        strRequestParams += "Content-Type:";
        strRequestParams += strMimeType;
        strRequestParams += (LINE_END + LINE_END);
        vecRequestParams.push_back(strRequestParams);
        vecFilePath.push_back(strFilePath);
        nFileSize += strRequestParams.length();
        nFileSize += FileCache::getFileSize(strFilePath);
    }
    string strTailParams = LINE_START+BOUNDARY+LINE_START+LINE_END;
    
    string strRequest;
    strRequest = "POST " + requestAddress + " HTTP/1.1\r\n";//%s %s HTTP/1.1\r\n
    
    vector<SMemPage> vecMemBuf;
    ((CMemPool*)Application::g_memPool)->MallocPage(vecMemBuf, 1);
    if(vecMemBuf.size() < 1) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "((CMemPool*)Application::g_memPool)->MallocPage(vecMemBuf, 1) == NULL");
        return false;
    }
    
    char* szBuf = vecMemBuf[0].m_point;
    if(nPort == 80 || nPort == 443)
        sprintf(szBuf, "Host:%s\r\n", strDomain.c_str());
    else
        sprintf(szBuf, "Host:%s:%d\r\n", strDomain.c_str(), nPort);
    strRequest += szBuf;
    
    cJSON* pNext = pHeader->child;
    while(pNext) {
        if(pNext->type == cJSON_String) {
            sprintf(szBuf, "%s:%s\r\n", pNext->string,pNext->valuestring);
            strRequest += szBuf;
        }
        
        if(pNext->type == cJSON_Number) {
            sprintf(szBuf, "%s:%f\r\n", pNext->string,pNext->valuedouble);
            strRequest += szBuf;
        }
        pNext = pNext->next; 
    }
    
    sprintf(szBuf, "Connection:Keep-Alive\r\n");
    strRequest += szBuf;
    
    string strHttpUrl = isHttps?"https://"+strDomainAndPort:"http://"+strDomainAndPort;
    if(Application::g_cookieManage != NULL && !ARKWEB_MEMBER_MISSING(Application::g_cookieManage, existCookies)) {
        if(Application::g_cookieManage->existCookies(false)) {
            if(!ARKWEB_MEMBER_MISSING(Application::g_cookieManage, fetchCookieSync)) {
                char* pCookieValue = NULL;
                Application::g_cookieManage->fetchCookieSync(strHttpUrl.c_str(), false, true, &pCookieValue);
                if(pCookieValue != NULL && strlen(pCookieValue) > 0) {
                    string strCookies = pCookieValue;
                    string strCookie = "Set-Cookie:";
                    size_t pos;
                    while ((pos = strCookies.find(strCookie)) != std::string::npos) {
                        strCookies.erase(pos, strCookie.length());
                    }
                    sprintf(szBuf, "Cookie:%s\r\n", strCookies.c_str());
                    strRequest += szBuf;
                }
                if(pCookieValue != NULL) {
                    OH_ArkWeb_ReleaseString(pCookieValue);
                }    
            }
        }
    }
    
    sprintf(szBuf, "Content-Length:%lu\r\n", nFileSize+strTailParams.size());
    strRequest += szBuf;
    
    sprintf(szBuf, "Keep-Alive:timeout=5, max=1000\r\n");
    strRequest += szBuf;
    
    sprintf(szBuf, "Content-Type: multipart/form-data; boundary=%s\r\n\r\n", BOUNDARY.c_str());
    strRequest += szBuf;
    ((CMemPool*)Application::g_memPool)->FreePage(vecMemBuf);
    
    ConnPoolManage* connPoolManage = (ConnPoolManage*)Application::g_connPoolManage;
    ConnPool* pool = connPoolManage->getConnPool(strDomain);
    if(pool == NULL) {
        return false;
    }
    
    vector<SMemPage>  vecMemPage;
    if(isHttps) {
        bool isClose = true;
        SSL* ssl = NULL;
        if(!pool->getSSL(&ssl, nPort, m_nTLSVersion, connectTimeout,  m_strCAFilePathName, m_strClientCertPathName, m_strClientKeyPathName)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->getSSL(&ssl, nPort, connectTimeout, m_strCAFilePathName, m_strClientCertPathName, m_strClientKeyPathName) == false");
        }else if(!pool->uploadFileWithTimeOuts(ssl, strRequest, strTailParams, vecRequestParams, vecFilePath, pMaxBuffer, nBufSize, std::ref(pRequest->getAbort()), NULL, readTimeout)&& !pRequest->getAbort()) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN,"CordovaHttpPlugin","pool->uploadFileWithTimeOuts(...) == false");
        }else if(!pRequest->getAbort() && !pool->recvHttpWithTimeOut(ssl,  "POST", vecMemPage, pMaxBuffer, nBufSize, isClose, std::ref(pRequest->getAbort()), readTimeout)) {
            ((CMemPool*)Application::g_memPool)->FreePage(vecMemPage);
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin","pool->recvHttpWithTimeOut(ssl, requestAddress, pMaxBuffer, nBufSize, isReconnect) == false");
        }
        pool->freeSocket(ssl, true);
    } else {
        bool isClose = false;
        int nSocket = -1;
        if(!pool->getSocket(nSocket,nPort, connectTimeout)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin",  "pool->getSocket(nSocket) == false");
        }else if(!pool->uploadFileWithTimeOuts(nSocket, strRequest, strTailParams, vecRequestParams, vecFilePath, pMaxBuffer, nBufSize, std::ref(pRequest->getAbort()), NULL, readTimeout) && !pRequest->getAbort()) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin",  "pool->uploadFileWithTimeOuts(...) == false");
        }else if(!pRequest->getAbort() && !pool->recvHttpWithTimeOut(nSocket, "POST", vecMemPage, pMaxBuffer, nBufSize, isClose, std::ref(pRequest->getAbort()), readTimeout)) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CordovaHttpPlugin", "pool->recvHttpWithTimeOut(nSocket, requestAddress, pMaxBuffer, nBufSize, isReconnect) == false");
        }
        pool->freeSocket(nSocket, true);
    }
    
    if(pRequest->getAbort()) {
        cJSON* pResponse = cJSON_CreateObject();
        cJSON_AddNumberToObject(pResponse, "status", -8);
        cJSON_AddStringToObject(pResponse, "error", "User canceled");
        cbc.error(pResponse);
        cJSON_Delete(pResponse);
        return true;
    }
    
    if(vecMemPage.empty()) {
        return false;
    }
    
    int httpCode = pool->getHttpCode(vecMemPage[0].m_point, vecMemPage[0].m_nCount);
    if(httpCode == 0) {
        ((CMemPool*)Application::g_memPool)->FreePage(vecMemPage);
        return false;
    }
    
    if(followRedirect && HttpCode::isRedirection(httpCode)) {
        string strLocation = pool->getHttpLocation(vecMemPage[0].m_point, vecMemPage[0].m_nCount);
        if(!strLocation.empty() && strLocation != urlPath) {
            cJSON* pUrl = cJSON_CreateString(strLocation.c_str());
            cJSON_ReplaceItemInArray(pJson, 0, pUrl);
            uploadFiles(pJson,cbc,pTmp, nBufSize, pRequest);
        }
        return true;
    }
    
    map<string, string> mapRespHeaders;
    if(!pool->getHttpHeaders(vecMemPage[0].m_point, vecMemPage[0].m_nCount,mapRespHeaders)) {
        ((CMemPool*)Application::g_memPool)->FreePage(vecMemPage);
        return false;
    }
    
    cJSON* pResponseHeader = cJSON_CreateObject();
    for(map<string,string>::iterator iter = mapRespHeaders.begin(); iter != mapRespHeaders.end(); ++iter){
        cJSON_AddStringToObject(pResponseHeader, iter->first.c_str(), iter->second.c_str());
    }
    cJSON* pResponse = cJSON_CreateObject();
    cJSON_AddNumberToObject(pResponse, "status", httpCode);
    cJSON_AddStringToObject(pResponse, "url", urlPath.c_str());
    cJSON_AddItemToObject(pResponse, "headers", pResponseHeader);
    
    vector<char> vecResponseBody;
    int nBodyPos = pool->getHttpHeader(vecMemPage[0].m_point, vecMemPage[0].m_nCount);
    for(int i=0; i<vecMemPage.size(); i++) {
        char* pResData = NULL;
        int nResLength = 0;
        if(i == 0)  {
            pResData = vecMemPage[i].m_point + nBodyPos;
            nResLength = vecMemPage[i].m_nCount - nBodyPos;
            
        } else {
            pResData = vecMemPage[i].m_point;
            nResLength = vecMemPage[i].m_nCount;
        }
       vecResponseBody.insert(vecResponseBody.end(), pResData, pResData+nResLength);
    }
    
    if(responseType == "text" || responseType == "json") {
        string strResponseBody;//返回默认utf-8编码
        strResponseBody.insert(strResponseBody.begin(), vecResponseBody.begin(), vecResponseBody.begin()+vecResponseBody.size());
        cJSON_AddStringToObject(pResponse, "data", strResponseBody.c_str());
    } else {
        string strResponseBody = CBase64::encode((char*)&vecResponseBody[0], vecResponseBody.size());
        cJSON_AddStringToObject(pResponse, "data", strResponseBody.c_str());
    }
    cbc.success(pResponse);
    cJSON_Delete(pResponse);
    return true;
}